package todo;

import done.AbstractWashingMachine;
import se.lth.cs.realtime.*;


public class WaterController extends PeriodicThread {
    // TODO: add suitable attributes
    public static final int WATER_IDLE  = 0;

    /** Fill water to a given level */
    public static final int WATER_FILL  = 1;

    /** Drain, leave drain pump running when finished */
    public static final int WATER_DRAIN = 2;
    
    AbstractWashingMachine theMachine;
    int mode;
	double targetlevel;
	boolean changeAck;
	boolean onoff;
	WaterEvent tmp;
	WaterEvent e;

    public WaterController(AbstractWashingMachine theMachine, long speed) {
	super(speed); // TODO: replace with suitable period
	mode = WATER_IDLE;
	this.theMachine = theMachine;
	targetlevel = 0.5;
	changeAck = false;
    }

    public void perform() {
    	
    	WaterEvent tmp = (WaterEvent) mailbox.tryFetch();
    	if(tmp!= null){
    		e = tmp;
    		targetlevel = e.getLevel();
    		mode = e.getMode();
    		changeAck = true;
    		System.out.println("WaterC mode: " + mode + "Source: " + e.getSource());
    		
     	}
    	
    	if(mode == WATER_IDLE){
    		theMachine.setDrain(false);
    		theMachine.setFill(false);
//    		if(changeAck){
//    			System.out.println("Water idle ack");
//    			((WashingProgram)e.getSource()).putEvent(new AckEvent(this));
//    			changeAck = false;
//    		}
    		
    	}else if(mode == WATER_FILL){
    		System.out.println("Water fill");
    			onoff = true;
        		
        		if(theMachine.getWaterLevel() >= targetlevel){
        			System.out.println("Lvl reached...................");
            		onoff = false;
            		if(changeAck){         
            			System.out.println("Water Full ack");
            			((WashingProgram)e.getSource()).putEvent(new AckEvent(this));
            			changeAck = false;
            			
            		}
            	}
        		theMachine.setDrain(false);
        		theMachine.setFill(onoff);
   
    	}else if(mode == WATER_DRAIN){
    		
    		if(theMachine.getWaterLevel() == 0){
    			if(changeAck){
    				System.out.println("Water Drain");
        			((WashingProgram)e.getSource()).putEvent(new AckEvent(this));
    				changeAck = false;
    			}
    			
    		}
    		
    		theMachine.setDrain(true);
    		theMachine.setFill(false);
    		
    	}
    	
    	    	
    }
}



















